from django.shortcuts import render

# Create your views here.
from rest_framework.authentication import TokenAuthentication

from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from .filters import GoodsFilter
from .serializers import GoodsSerializer,CategorySerializer,BannerSerializer,IndexCategorySerializer,HotWordsSerializer
from .models import Goods,GoodsCategory,Banner,HotSearchWords

from rest_framework import mixins
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import filters

from django_filters.rest_framework import DjangoFilterBackend
# 设置登录与未登录限速
from rest_framework.throttling import  UserRateThrottle,AnonRateThrottle
from rest_framework_extensions.cache.mixins import CacheResponseMixin


class GoodsPagination(PageNumberPagination):
    page_size = 12
    # 向后台要多少条
    page_size_query_param = 'page_size'
    # 定制多少业的参数
    page_query_param = 'page'
    max_page_size = 100


class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    '''商品列表页。分页，搜索，过滤，排序，取某一个商品的详情'''

    throttle_classes = (UserRateThrottle,AnonRateThrottle)
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    queryset = Goods.objects.all()

    # 设置常用过滤器
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    # 设置排序
    ordering_fields = ('sold_num','shop_price')
    # 设置为自定义的类
    filter_class = GoodsFilter

    # 设置search字段
    search_fields = ('name','goods_brief','goods_desc')

    # 商品点击数+1
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class CategoryViewset(mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    '''商品分类列表数据'''
    queryset = GoodsCategory.objects.filter(category_type = 1)
    serializer_class = CategorySerializer


class BannerViewset(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''获取轮播图'''
    queryset = Banner.objects.all().order_by('index')
    serializer_class = BannerSerializer


class IndexCategoryViewset(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''首页商品分类数据'''
    queryset = GoodsCategory.objects.filter(is_tab=True,name__in=["生鲜食品", "酒水饮料"])
    serializer_class = IndexCategorySerializer


class HotSearchsViewset(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''热搜列表'''
    queryset = HotSearchWords.objects.all().order_by('-index')
    serializer_class = HotWordsSerializer